package com.sotb.receiver;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
/**
 * @author zsr
 * 地图的第一层图层
 */
public class FirstOverlay extends ItemizedOverlay<OverlayItem>{
	private ArrayList<OverlayItem> overlayItems = new ArrayList<OverlayItem>();
	private MainMapActivity locationReceiverActivity;
	private Handler handler;
	private Message msg;
	
	
	/**
	 * 标记层的构造函数
	 * @param defaultMarker	用于指定标记所使用的默认图片
	 * @param context		
	 */
	public FirstOverlay(Drawable defaultMarker,Context context){
		//必须调用父类的构造函数
		super(boundCenterBottom(defaultMarker));
		this.locationReceiverActivity = (MainMapActivity)context;
		this.handler = locationReceiverActivity.smsHandler;
		
	}
	
	/**
	 * 添加标记
	 * @param overlayItem
	 */
	public void addOverlayItem(OverlayItem overlayItem){
		overlayItems.add(overlayItem);
		populate();		//增加item后必须调用:为item的绘制做准备
	}
	
	/**
	 * 移除标记
	 * @param phoneNum	想要移除的标记对应的号码
	 */
	public void removeOverlayItem(String phoneNum){
		int size = overlayItems.size();
		for(int i = 0; i < size; i++){
			if(overlayItems.get(i).getTitle().equals(phoneNum)){
				setLastFocusedIndex(-1); 
				overlayItems.remove(i);
				populate();	
				return;
			}
		}
	}
	
	public void removeAllOverlayItem(){
		setLastFocusedIndex(-1); 
		overlayItems.clear();
		populate();	
	}
	
	//为polulate()读取item服务
	@Override
	protected OverlayItem createItem(int i) {
		return overlayItems.get(i);
	}

	@Override
	public int size() {
		return overlayItems.size();
	}

	@Override
	protected boolean onTap(int index) {
		System.out.println("index " + index + " was tapped");
		OverlayItem item = overlayItems.get(index);
		AlertDialog.Builder builder = new AlertDialog.Builder(locationReceiverActivity);
		builder.setTitle("求助点信息");
		builder.setMessage("电话： " + item.getTitle());
		msg = this.handler.obtainMessage();
		msg.obj = item.getTitle();
		builder.setPositiveButton("接警完成", new PositiveButtonListener());
		builder.setNegativeButton("返回", null);
		Dialog dialog = builder.create();
		dialog.show();
		return true;
	}
	
	
	class PositiveButtonListener implements OnClickListener{

		public void onClick(DialogInterface dialog, int which) {
			msg.what = Constant.COMPLETE;
			handler.sendMessage(msg);
		}
	}
	
}
